<script setup>
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { onShareAppMessage, onLoad } from '@dcloudio/uni-app'
import { useWallpaperStore } from '@/store/wallpaper.js'
import { getStatusBarHeight } from '@/utils/system.js'
import { calculateSHA256 } from '@/utils/calculateHash.js'
import request from '@/utils/request'
import API from '@/utils/API'
import dayjs from 'dayjs'

const useWallpaper = useWallpaperStore()

const wallpaperList = computed(() => useWallpaper.wallpaperList)
const currIndex = computed(() => useWallpaper.currIndex)

const swiperChange = (e) => {
	useWallpaper.currIndex = e.detail.current
}

const type = ref('')

onLoad(async (options) => {
	if (options.type == 'share') {
		type.value = 'share'
		
		const { data } = await request({
			url: API.getDetailWall,
			data: {
				id: options.id
			}
		})
		
		console.log(data)
		useWallpaper.wallpaperList = useWallpaper.wallpaperList.concat(data.map(item => {
			return {
				...item,
				picurl: item.smallPicurl.replace('_small.webp', '.jpg')
			}
		}))
		useWallpaper.currIndex = 0
	}
})

// 分享给好友
onShareAppMessage((e) => {
	console.log(e)
	return {
		title: '咸虾米壁纸',
		path: `/pages/preview/preview?type=share&id=${wallpaperList.value[currIndex.value]._id}`
	}
})

// 图片懒加载
const shouldShowImage = (index) => {
  const total = wallpaperList.value.length
  
  // 当前页、前一页、后一页
  const isAdjacent = currIndex.value >= index - 1 && currIndex.value <= index + 1
  
  // 首尾循环
  const isLoopEdgeCase = 
    (currIndex.value === 0 && index === total - 1) || 
    (currIndex.value === total - 1 && index === 0)
  
  return isAdjacent || isLoopEdgeCase
}

const now = ref(new Date())

// 显示遮罩层
const showMask = ref(true)

const switchMask = () => {
	showMask.value = !showMask.value
}

// 壁纸信息
const infoPopup = ref(null)

const infoClick = () => {
	infoPopup.value.open()
}

const clickInfoClose = () => {
	infoPopup.value.close()
}

// 评分弹窗
const starPopup = ref(null)

const starClick = () => {
	userScore.value = 0
	starPopup.value.open()
}

const clickScoreClose = () => {
	starPopup.value.close()
}

const userScore = ref(0)

// 提交评分
const submitScore = async () => {
	clickScoreClose()
	const res = await request({
		url: API.setScore,
		data: {
			classid: wallpaperList.value[currIndex.value].classid,
			wallId: wallpaperList.value[currIndex.value]._id,
			userScore: userScore.value
		}
	})
	
	// console.log(res)
	if (res.errCode === 0) {
		uni.showToast({
			title: '评分成功',
			icon: 'none'
		})
	}
}

// 下载壁纸
const downloadImg = async () => {
	const res = await request({
		url: API.downloadWall,
		data: {
			classid: wallpaperList.value[currIndex.value].classid,
			wallId: wallpaperList.value[currIndex.value]._id
		}
	})
	console.log(res)
	
	// #ifdef H5
		try {
			const imageUrl = wallpaperList.value[currIndex.value].picurl
			
			const response = await fetch(imageUrl)
			if (!response.ok) throw new Error('网络请求失败')
			
			// 转换为 Blob
			const blob = await response.blob()
			const blobUrl = URL.createObjectURL(blob)
			
			const link = document.createElement('a')
			link.href = blobUrl
			const hash = await calculateSHA256(blob)
			link.download = 'wallpaper_' + dayjs().format('YYMMDD') + '_' + hash.slice(0, 6)
			
			document.body.appendChild(link)
			link.click()
			document.body.removeChild(link)
			
			URL.revokeObjectURL(blobUrl)
		} catch (err) {
			console.error('下载失败:', err)
		}
	// #endif
	
	// #ifndef H5
		uni.showLoading({
			title: '下载中...',
			mask: true
		})
		
		uni.getImageInfo({
			src: wallpaperList.value[currIndex.value].picurl,
			success: (res) => {
					console.log('res', res)
					uni.saveImageToPhotosAlbum({
						filePath: res.path,
						success: () => {
							console.log('save success')
						},
						fail: (err) => {
							// console.log(err)
							if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') {
								uni.showToast({
									title: '取消保存',
									icon: 'none'
								})
								return
							}
							
							uni.showModal({
								title: '授权保存到相册',
								success: (res) => {
									if (res.confirm) {
										uni.openSetting({
											success: (setting) => {
												console.log('setting', setting)
												if (setting.authSetting['scope.writePhotosAlbum']) {
													uni.showToast({
														title: '授权成功',
														icon: 'none'
													})
												} else {
													uni.showToast({
														title: '授权失败',
														icon: 'none'
													})
												}
											}
										})
									}
								}
							})
						},
						complete: () => {
							uni.hideLoading()
						}
					})
				}
		})
	// #endif
}

const goback = () => {
	if (type.value === 'share') {
		uni.reLaunch({
			url: '/pages/index/index'
		})
	} else {
		uni.navigateBack()
	}
}

// 定时更新时间
let intervalId = null

onMounted(() => {
  intervalId = setInterval(() => {
    now.value = new Date()
  }, 60000)
})

onUnmounted(() => {
	intervalId = null
})
</script>

<template>
	<view class="preview">
		<swiper circular :current="currIndex" @change="swiperChange">
			<swiper-item v-for="(item, index) in wallpaperList" :key="item._id">
				<view class="image-box" @click="switchMask">
					<image v-if="shouldShowImage(index)" :src="item.picurl" mode="aspectFill"></image>
				</view>
			</swiper-item>
		</swiper>
		
		<view class="mask" v-show="showMask">
			<view class="goback mask-item" @click="goback" :style="{ top: getStatusBarHeight() + 'px', left: '80rpx' }">
				<view class="icon">
					<uni-icons type="left" size="22" color="$uni-text-color-1"></uni-icons>
				</view>
			</view>
			
			<view class="top mask-item">
				<view class="count">
					{{ currIndex + 1 }} / {{ wallpaperList.length }}
				</view>
				<view class="time">
					<uni-dateformat :date="now" format="hh:mm"></uni-dateformat>
				</view>
				<view class="date">
					<uni-dateformat :date="now" format="M月d日"></uni-dateformat>
				</view>
			</view>
			
			<view class="footer mask-item">
				<view class="box" @click="infoClick">
					<uni-icons type="info" size="28"></uni-icons>
					<view class="text">信息</view>
				</view>
				<view class="box" @click="starClick">
					<uni-icons type="star" size="28"></uni-icons>
					<view class="text">{{ wallpaperList[currIndex].score }}分</view>
				</view>
				<view class="box" @click="downloadImg">
					<uni-icons type="download" size="28"></uni-icons>
					<view class="text">下载</view>
				</view>
			</view>
			
			<!-- 详情弹窗 -->
			<uni-popup ref="infoPopup" type="bottom">
				<view class="infoPopup">
					<view class="popHeader">
						<view></view>
						<view class="title">壁纸信息</view>
						<view class="close" @click="clickInfoClose">
							<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
						</view>
					</view>
					<scroll-view scroll-y>
						<view class="content">
							<view class="row">
								<view class="label">壁纸ID：</view>
								<text user-select="auto" class="value">{{ wallpaperList[currIndex]._id }}</text>
							</view>
							
							<view class="row">
								<view class="label">分类：</view>
								<text class="value class">明星美女</text>
							</view>
							
							<view class="row">
								<view class="label">发布者：</view>
								<text class="value">{{ wallpaperList[currIndex].nickname }}</text>
							</view>
							
							<view class="row">
								<text class="label">评分：</text>
								<view class='value roteBox'>
									<uni-rate readonly :value="wallpaperList[currIndex].score" size="16"/>
									<text class="score">{{ wallpaperList[currIndex].score }}分</text>
								</view>
							</view>
							
							<view class="row">
								<text class="label">摘要：</text>
								<view class='value'>
									{{ wallpaperList[currIndex].description }}
								</view>
							</view>
							
							<view class="row">
								<text class="label">标签：</text>
								<view class='value tabs'>
									<view class="tab" v-for="(tab, index) in wallpaperList[currIndex].tabs" :key="index">
										{{ tab }}
									</view>
								</view>
							</view>	
							
							<view class="copyright">
								声明：本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸，维护您的权益。
							</view>
						</view>
					</scroll-view>
				</view>
			</uni-popup>
			
			<!-- 评分弹窗 -->
			<uni-popup ref="starPopup" type="center" :animation="false">
				<view class="scorePopup">
					<view class="popHeader">
						<view></view>
						<view class="title">壁纸评分</view>
						<view class="close" @click="clickScoreClose">
							<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
						</view>
					</view>
					
					<view class="content">
						<uni-rate v-model="userScore" allowHalf />
						<text class="text">{{userScore}}分</text>
					</view>
					
					<view class="footer">
						<button @click="submitScore" :disabled="!userScore" type="default" size="mini" plain >确认评分</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<style scoped lang="scss">
.preview {
	position: relative;
	
	swiper {
		width: 750rpx;
		height: 100vh;
		
		.image-box {
			width: 100%;
			height: 100%;
			
			image {
				width: 100%;
				height: 100%;
			}
		}
	}
	
	.mask {
		.mask-item {
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
		}
		
		.goback {
			background-color: rgba(0, 0, 0, 0.5);
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			width: 80rpx;
			height: 80rpx;
			color: $uni-text-color-2;
			border: 1px solid $uni-gray-2;
			
			.icon {
				transform: translateX(-3rpx);
			}
		}
		
		.top {
			top: 10vh;
			width: 750rpx;
			text-align: center;
			color: $uni-text-color-1;
			
			.count {
				padding: 2rpx 26rpx 5rpx 26rpx;
				border-radius: 50rpx;
				background-color: rgba(0, 0, 0, 0.5);
				color: $uni-text-color-2;
				display: inline-block;
				font-size: 24rpx;
				backdrop-filter: blur(3rpx);
			}
			
			.time {
				font-size: 100rpx;
			}
		}
		
		.footer {
			display: flex;
			justify-content: space-around;
			bottom: 10vh;
			background-color: rgba(255, 255, 255, 0.8);
			padding: 10rpx;
			border-radius: 100rpx;
			width: 60vw;
			
			.box {
				text-align: center;
				.text {
					font-size: 28rpx;
					color: $uni-gray-1;
				}
			}
		}
	}
	
	.popHeader{
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: relative;
		
		.title{
			color: $uni-text-color-3;
			font-size: 26rpx;
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
		}
		
		.close{				
			padding:6rpx;
		}
	}
	
	.infoPopup {
		background: #fff;
		padding: 30rpx;
		border-radius: 30rpx 30rpx 0 0;
		overflow: hidden;		
		
		scroll-view {
			max-height: 60vh;
			
			.content{
				.row{
					display: flex;
					padding:16rpx 0;
					font-size: 32rpx;
					line-height: 1.7em;
					
					.label{
						color: $uni-text-color-3;
						width: 140rpx;
						text-align: right;
						font-size: 30rpx;
					}
					
					.value{
						flex:1;
						width:0;
					}
					
					.roteBox{
						display: flex;
						align-items: center;
						
						.score{
							font-size: 26rpx;
							color: black;
							padding-left:10rpx;
						}
					}
					
					.tabs{
						display: flex;
						flex-wrap: wrap;
						.tab{
							border: 1px solid $uni-main-color;
							color: $uni-main-color;
							font-size: 22rpx;
							padding: 10rpx 30rpx;
							border-radius: 40rpx;
							line-height: 1em;
							margin: 0 10rpx 10rpx 0;
						}
					}
					
					.class{
						color: $uni-main-color;
					}
				}
				
				.copyright {
					font-size: 28rpx;
					padding: 20rpx;
					background: #F6F6F6;
					color: #666;
					border-radius: 10rpx;
					margin: 20rpx 0;
					line-height: 1.6em;
				}
			}
		}
	}
	
	.scorePopup{
		background: #fff;
		padding:30rpx;
		width: 70vw;
		border-radius: 30rpx;
		
		.content{
			padding:30rpx 0;
			display: flex;
			justify-content: center;
			align-items: center;
			
			.text{
				color: #FFCA3E;
				padding-left: 10rpx;
				width: 80rpx;
				line-height: 1em;
				text-align: right;
			}
		}
		
		.footer{
			padding:10rpx 0;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
}
</style>
